<?php

namespace Frieza\Modules\Creators\Controllers;

use App\Exceptions\InputErrorException;
use Doraemon\model\Member;
use Doraemon\model\Task\TaskGroup as mTaskGroup;
use Doraemon\model\Task\UserTaskInfo;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Form;
use Doraemon\pockets\excel\DownExcel;
use Illuminate\Support\MessageBag;

class ImportController
{
    const PATH = '/home/adm_rsync_dir/limit_time_task.json';

    public function index(Content $content, Request $request)
    {
        $content->header('限时任务导入')->description(' ');

        $form = new Form();
        $form->text('topic_id', '话题id')->required()->rules();
        $form->text('task_id', '任务id')->required();
        $form->radio('has_wiki', '是否带wiki')->options([0 => '否', 1 => '是'])->default(0);
        $form->action('/admin/creators/import/edit');
        $content->row($form);
        return $content;
    }

    public function edit(Request $request)
    {
        $params = $request->all();

        if ($params['topic_id'] <= 0 || $params['task_id'] <= 0) {
            $error = new MessageBag([
                'title' => '请正确配置话题及任务id'
            ]);
            return back()->withInput()->with(compact('error'));
        }

        $content = file_get_contents(self::PATH);
        $content = $content ? json_decode($content, true) : [];
        $content[$params['topic_id']] = ['task_id' => $params['task_id'], 'has_wiki' => $params['has_wiki']];
        file_put_contents(self::PATH, json_encode($content, JSON_UNESCAPED_UNICODE));
        $success = new MessageBag([
            'title' => '提交成功'
        ]);
        return back()->withInput()->with(compact('success'));
    }

}